#include "sortthread.h"
#include <ctime>
#include <QMessageBox>
#include <malloc.h>


/*整数拆分函数*/
/*传出三位数中的个十百位上的数值*/
int getdigit(int x, int d)
{
    int a[] = { 1, 1, 10, 100 };
    return (x / a[d]) % 10;
}

/*基数排序函数*/
void SortThread::radixSort(int arr[], int begin, int end, int d)
{
    sortTle = 0;
    sortMov = 0;
    sortCmp = 0;
    const int radix = 10;
    int count[radix], i, j;
    int *bucket = (int*)malloc((end - begin + 1)*sizeof(int));
    for (int k = 1; k <= d; ++k)
    {
        this->sendt(sortTle,sortMov,sortCmp);
        this->senda(catched1,-1);
        sortTle++;
        for (i = 0; i < radix; i++)
        {
            count[i] = 0;
        }

        for (i = begin; i <= end; i++)
        {
            count[getdigit(arr[i], k)]++;
        }

        for (i = 1; i < radix; i++)
        {
            count[i] = count[i] + count[i - 1];
        }

        for (i = end; i >= begin; --i)
        {
            sortCmp++;
            this->sendt(sortTle,sortMov,sortCmp);
            j = getdigit(arr[i], k);
            bucket[count[j] - 1] = arr[i];
            sortMov++;
            --count[j];
            catched1 = i;
            this->sendArray[i] =  arr[i];
            this->senda(catched1,-1);
            //sortMov++;
        }


        for (i = begin, j = 0; i <= end; ++i, ++j)
        {
            sortCmp++;
            this->sendt(sortTle,sortMov,sortCmp);
            arr[i] = bucket[j];
            sortMov++;
            catched1 = i;
            this->sendArray[i] =  arr[i];
            this->senda(catched1,-1);
        }
        for (int i = 0; i < this->size; ++i)
        {
            sortCmp++;
            this->sendt(sortTle,sortMov,sortCmp);
            if (arr[i] < 0)
            {
                continue;
            }
            catched1 = i;
            this->sendArray[i] =  arr[i];
            this->senda(catched1,-1);
        }
        //this->sendt(sortTle,sortMov,sortCmp);
        //this->senda(catched1,-1);
    }
    free(bucket);
    for(int i = 0; i < size; i++)
    {
        senda(i,-10);
    }
}
